<?php
/* This file is part of Mirasol CMS
   (C) 2011-2012 by Chris Alban Hansen.
   Released under the terms of the GNU General Public License.
   See COPYING in the top level directory of the Mirasol CMS installation. */

include "{$_SERVER['DOCUMENT_ROOT']}/includes/config.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/settings.php";
include "{$_SERVER['DOCUMENT_ROOT']}/includes/xmlfeed.php";

if ($loadsubpage == 1)
{
  $slid = isset ($_GET['slid']) ? $_GET['slid'] : 0;
  $tid = isset ($_GET['tid']) ? $_GET['tid'] : 0;
  
  /* Get site name */
  $sitename = htmlentities (getsetting ($connection, "sitename"), ENT_COMPAT, "UTF-8", false);
  $domainname = htmlentities (getsetting ($connection, "domainname"), ENT_COMPAT, "UTF-8", false);
  $protocol = getsetting ($connection, "protocol");
?>
<h1>
  <?=$sitename?>
  <a href="<?=$protocol?>://<?=$domainname?>/" title="Go to website" rel="external"><img src="./images/link.gif" alt="<?=$sitename?>" class="externallink" /></a>
</h1>

<div id="templates">
  <h3>Templates</h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_templates)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $name = htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl";
        print "<tr><td><a href=\"./?p=templates&amp;tid={$row['id']}\"><strong>$name</strong></a></td>";
        print "<td class=\"alignright\"><a href=\"javascript:deltemplate('$name', {$row['id']});\" title=\"Delete '$name'\"><strong>&times;</strong></a></td></tr>\n";
      }
  }
mysql_free_result ($result);
?>
  </table>

  <div id="addnew1">
    <p>
      <input type="button" value="+" onclick="document.getElementById('addnew2').style.display='block';" class="button" />
      Add new template
    </p>
  </div>

  <div id="addnew2">
    <form action="../includes/addtemplate.php" method="post">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td><strong>Name:</strong>&nbsp;</td>
          <td><input type="text" name="name" value="Type_name_here" maxlength="50" class="textfield friendly" />.xsl</td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Add &raquo;" class="button" /></td>
        </tr>
      </table>
    </form>
  </div>
  
  <div id="separator">&nbsp;</div>

  <h3>Sublayouts</h3>
  <table cellpadding="0" cellspacing="0" style="width: 100%">
<?php
/* Print the list of templates */
$result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_sublayouts)." ORDER BY name");
if (mysql_num_rows ($result) > 0)
  {
    while ($row = mysql_fetch_array ($result))
      {
        $name = htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false).".xsl";
        print "<tr><td><a href=\"./?p=templates&amp;slid={$row['id']}\"><strong>$name</strong></a></td>";
        print "<td class=\"alignright\"><a href=\"javascript:delsublayout('$name', {$row['id']});\" title=\"Delete '$name'\"><strong>&times;</strong></a></td></tr>\n";
      }
  }
mysql_free_result ($result);
?>
  </table>

  <div id="addnew3">
    <p>
      <input type="button" value="+" onclick="document.getElementById('addnew4').style.display='block';" class="button" />
      Add new sublayout
    </p>
  </div>

  <div id="addnew4">
    <form action="../includes/addsublayout.php" method="post">
      <table cellpadding="0" cellspacing="0">
        <tr>
          <td><strong>Name:</strong>&nbsp;</td>
          <td><input type="text" name="name" value="Type_name_here" maxlength="50" class="textfield friendly" />.xsl</td>
        </tr>
        <tr>
          <td colspan="2"><input type="submit" value="Add &raquo;" class="button" /></td>
        </tr>
      </table>
    </form>
  </div>
</div>

<div id="editor">
<?php
/* If no template is selected... */
if (empty ($tid) && empty ($slid))
{
?>
  <div id="info">
    <p>&larr; Click on an item in the list to edit it.</p>
  </div>
<?php
}
else
{
?>
    <div id="tabs">
      <ul>
<?php
if (!empty ($tid) && empty ($slid))
{
?>
        <li><a href="javascript:switchtabs ('tab1');">Template</a></li>
        <li><a href="javascript:switchtabs ('tab2');">Parameters</a></li>
        <?php if (getsetting ($connection, "use_datasheets") == 1) print "<li><a href=\"javascript:switchtabs ('tab3');\">Datasheets</a></li>"; ?>
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
        <li><span>Sublayout</span></li>
<?php
}
?>
      </ul>
    </div>
    
<?php
if (!empty ($tid) && empty ($slid))
{
?>
    <form action="../includes/savetemplate.php" method="post">
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
    <form action="../includes/savesublayout.php" method="post">
<?php
}
?>
<?php
if (!empty ($tid) && empty ($slid))
{
?>
      <div id="tab1">
<?php
  $result = mysql_query ("SELECT name, fields, xslt FROM ".db_maketablename ($table_templates)." WHERE id='$tid'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      $layout = htmlentities ($row['xslt'], ENT_COMPAT, "UTF-8", true);
      
      /* Parse fields and xmlfeed */
      print "<label>Name</label><br /><input type=\"text\" name=\"templatename\" value=\"".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false)."\" class=\"textfield friendly\" />\n";
      
      /* Prepare the XML parser and parse the data */
      $xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n".$row['fields'];     
      $xmlres = xml_parser_create ("utf-8");
      xml_parse_into_struct ($xmlres, $xmldata, $values);
      xml_parser_free ($xmlres);
?>
        <table cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <td class="col1"><label>Field name</label></td>
              <td class="col2"><label>Label</label></td>
              <td class="col3"><label>Type</label></td>
              <td class="col4">&nbsp;</td>
            </tr>
          </thead>
          
          <tbody>
<?php
      /* Walk through the tags */
      $i = 0;
      $fieldcount = 0;
      while (!empty ($values[$i]))
        {
          if ($values[$i]['level'] == 2 && strcasecmp ($values[$i]['tag'], "field") == 0 && isset ($values[$i]['attributes']['NAME']) && isset ($values[$i]['attributes']['LABEL']) && isset ($values[$i]['attributes']['TYPE']))
            {
              $fieldcount++;
              print "<tr>";
              print "<td class=\"col1\"><input type=\"text\" name=\"name$fieldcount\" value=\"{$values[$i]['attributes']['NAME']}\" class=\"smalltextfield friendly\" /></td>";
              print "<td class=\"col2\"><input type=\"text\" name=\"label$fieldcount\" value=\"{$values[$i]['attributes']['LABEL']}\" class=\"smalltextfield friendly\" /></td>";
              print "<td class=\"col3\"><select name=\"type$fieldcount\">";
              foreach ($fieldtypes as $type)
                {
                  $sel = $values[$i]['attributes']['TYPE'] == $type ? " selected=\"selected\"" : "";
                  print "<option value=\"$type\"$sel>$type</option>";
                }
              print "</select></td>";
              print "<td><input type=\"submit\" name=\"delfield$fieldcount\" value=\"-\" class=\"alignright\" /></td>";
              print "</tr>\n";
            }
          $i++;
        }
?>
          </tbody>
        </table>
        
        <p>
          <input type="submit" name="addfield" value="+" />
          <span class="addfield">Add new field</span>
        </p>
        
        <label>Layout</label>
        <textarea id="xslt" name="templatelayout" rows="1" cols="1"><?=$layout?></textarea>
        <script type="text/javascript">
          //<![CDATA[
            var editor = CodeMirror.fromTextArea (document.getElementById ("xslt"), { mode: { name: "xmlpure" } });
          //]]>
        </script>
<?php
    }
  mysql_free_result ($result);
?>
      </div>
      
      <div id="tab2">
        <table cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <td class="col1"><label>Stylesheet</label></td>
              <td class="col2"><label>Identifier</label></td>
              <td class="col3"><label>Linked</label></td>
              <td class="col4">&nbsp;</td>
            </tr>
          </thead>
          
          <tbody>
<?php
  /* Get all styles */
  $styles = "";
  $result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_styles)." ORDER BY name ASC");
  if (mysql_num_rows ($result) > 0)
    {
      while ($row = mysql_fetch_array ($result))
        $styles[$row['id']] = $row['name'];
    }
  mysql_free_result ($result);

  /* Get related styles */
  $result = mysql_query ("SELECT id, style_id, identifier, linked FROM ".db_maketablename ($table_styles_rel)." WHERE template_id='$tid'");
  if (mysql_num_rows ($result) > 0)
    {
      $stylecount = 1;
      while ($row = mysql_fetch_array ($result))
        {
          print "<tr><td><select name=\"style_name$stylecount\">";
          if ($row['style_id'] == 0)
            print "<option value=\"0\" selected=\"selected\">* SELECT STYLE *</option>";
          foreach ($styles as $key => $style)
            {
              $sel = $key == $row['style_id'] ? " selected=\"selected\"" : "";
              print "<option value=\"$key\"$sel>$style.css</option>";
            }
          print "</select></td>";
          print "<td><input type=\"text\" name=\"style_identifier$stylecount\" value=\"".htmlentities ($row['identifier'], ENT_COMPAT, "UTF-8", false)."\" maxlength=\"20\" class=\"smalltextfield friendly\" /></td>";
          print "<td><select name=\"style_linked$stylecount\">";
          print "<option value=\"1\"";
          if ($row['linked'] == 1)
            print " selected=\"selected\"";
          print ">Linked</option>";
          print "<option value=\"0\"";
          if ($row['linked'] == 0)
            print " selected=\"selected\"";
          print ">Inline</option>";
          print "</select></td>";
          print "<td><input type=\"hidden\" name=\"style_id$stylecount\" value=\"{$row['id']}\" /><input type=\"submit\" name=\"delstyle$stylecount\" value=\"-\" class=\"alignright\" /></td>";
          print "</tr>";
          
          $stylecount++;
        }
    }
  mysql_free_result ($result);
?>
          </tbody>
        </table>

        <p>
          <input type="submit" name="addstyle" value="+" />
          <span class="addstyle">Add new style</span>
        </p>
        
        <p class="divider"></p>

        <table cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <td class="col1"><label>File</label></td>
              <td class="col2"><label>Identifier</label></td>
              <td class="col3">&nbsp;</td>
              <td class="col4">&nbsp;</td>
            </tr>
          </thead>
          
          <tbody>
<?php
/* Get related files */
$tbl_files = db_maketablename ($table_files);
$tbl_files_rel = db_maketablename ($table_files_rel);
$result = mysql_query ("SELECT $tbl_files_rel.id AS id, file_id, identifier, $tbl_files.filename_orig AS filename_orig FROM $tbl_files_rel LEFT JOIN $tbl_files ON $tbl_files.id=$tbl_files_rel.file_id WHERE template_id='$tid'");
if (mysql_num_rows ($result) > 0)
{
  $filecount = 1;
  while ($row = mysql_fetch_array ($result))
    {
      print "<tr>";
      print "<td><input type=\"text\" id=\"file_name$filecount\" name=\"filename$filecount\" value=\"".htmlentities ($row['filename_orig'], ENT_COMPAT, "UTF-8", false)."\" readonly=\"readonly\" class=\"tinytextfield friendly\"/>&nbsp;";
      print "<input type=\"button\" value=\"Pick\" onclick=\"opendialog ('pickfile.php?field1=file_name$filecount&field2=file_id$filecount', 970, 650);\" /></td>";
      print "<td colspan=\"2\"><input type=\"text\" name=\"file_identifier$filecount\" value=\"".htmlentities ($row['identifier'], ENT_COMPAT, "UTF-8", false)."\" class=\"smalltextfield friendly\"/></td>";
      print "<td><input type=\"hidden\" id=\"file_id$filecount\" name=\"file_id$filecount\" value=\"{$row['file_id']}\" /><input type=\"hidden\" name=\"filerel_id$filecount\" value=\"{$row['id']}\" /><input type=\"submit\" name=\"delfile$filecount\" value=\"-\" class=\"alignright\" /></td>";
      print "</tr>\n";
      
      $filecount++;
    }
}
mysql_free_result ($result);
?>
          </tbody>
        </table>

        <p>
          <input type="submit" name="addfile" value="+" />
          <span class="addstyle">Add new file</span>
        </p>
      </div>

      <div id="tab3">
<?php
if (getsetting ($connection, "use_datasheets") == 1)
{
  /* Get all datasheets */
  $datasheets = "";
  $result = mysql_query ("SELECT id, name FROM ".db_maketablename ($table_datasheets_def)." ORDER BY name ASC");
  if (mysql_num_rows ($result) > 0)
    {
      while ($row = mysql_fetch_array ($result))
        $datasheets[$row['id']] = $row['name'];
    }
  mysql_free_result ($result);
?>
        <table cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <td class="col1"><label>Datasheet</label></td>
              <td class="col2"><label>Identifier</label></td>
              <td class="col3"><label>Order</label></td>
              <td class="col4">&nbsp;</td>
            </tr>
          </thead>

<?php
/* Get related datasheets */
$tbl_datasheets_def = db_maketablename ($table_datasheets_def);
$tbl_datasheets_rel = db_maketablename ($table_datasheets_rel);
$result = mysql_query ("SELECT $tbl_datasheets_rel.id AS id, datasheet_id, identifier, order_field, order_asc, filter, fields FROM $tbl_datasheets_rel LEFT JOIN $tbl_datasheets_def ON $tbl_datasheets_def.id=$tbl_datasheets_rel.datasheet_id WHERE template_id='$tid'");
if (mysql_num_rows ($result) > 0)
{
  $datasheetcount = 1;
  while ($row = mysql_fetch_array ($result))
    {
      /* Get the field names */
      $fields_a = xmlfeed_fields ($row['fields']);
      $filter_s = htmlentities (stripslashes ($row['filter']), ENT_COMPAT, "UTF-8", false);
      
      print "<tr>";
      print "<td><select name=\"datasheet_name$datasheetcount\">";
      if ($row['datasheet_id'] == 0)
        print "<option value=\"0\" selected=\"selected\">* SELECT DATASHEET *</option>";
      foreach ($datasheets as $key => $datasheet)
        {
          $sel = $key == $row['datasheet_id'] ? " selected=\"selected\"" : "";
          print "<option value=\"$key\"$sel>$datasheet.xml</option>";
        }
      print "</select></td>";
      print "<td><input type=\"text\" name=\"datasheet_identifier$datasheetcount\" value=\"".htmlentities ($row['identifier'], ENT_COMPAT, "UTF-8", false)."\" maxlength=\"20\" class=\"smalltextfield friendly\" /></td>";
      print "<td><select name=\"datasheet_order_field$datasheetcount\">";
      print "<option value=\"0\">* NOT ORDERED *</option>";
      foreach ($fields_a as $fieldname)
        {
          $sel = $fieldname == $row['order_field'] ? " selected=\"selected\"" : "";
          print "<option value=\"$fieldname\"$sel>$fieldname</option>";
        }
      print "</select>&nbsp;<select name=\"datasheet_order_asc$datasheetcount\">";
      print "<option value=\"1\"";
      if ($row['order_asc'] == 1)
        print " selected=\"selected\"";
      print ">ASC</option>";
      print "<option value=\"0\"";
      if ($row['order_asc'] == 0)
        print " selected=\"selected\"";
      print ">DESC</option>";
      print "</select></td>";
      print "<td><input type=\"hidden\" name=\"datasheetrel_id$datasheetcount\" value=\"{$row['id']}\" /><input type=\"submit\" name=\"deldatasheet$datasheetcount\" value=\"-\" class=\"alignright\" /></td>";
      print "</tr>\n";
      print "<tr><td colspan=\"4\"><label>Filter</label><br/><textarea name=\"datasheet_filter$datasheetcount\" class=\"friendly filter\">$filter_s</textarea></td></tr>";
      
      $datasheetcount++;
    }
}
mysql_free_result ($result);
?>
        </table>
        
        <p>
          <input type="submit" name="adddatasheet" value="+" />
          <span class="addstyle">Add new datasheet</span>
        </p>
<?php
} /* getsetting ($connection, "use_datasheets") == 1 */
else
{
?>
        <!-- Pseudo -->
<?php
} /* getsetting ($connection, "use_datasheets") != 1 */
?>
      </div>
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
      <div id="tab1">
<?php
  $result = mysql_query ("SELECT name, xslt FROM ".db_maketablename ($table_sublayouts)." WHERE id='$slid'");
  if (mysql_num_rows ($result) > 0)
    {
      $row = mysql_fetch_array ($result);
      
      print "<label>Name</label><br /><input type=\"text\" name=\"sublayoutname\" value=\"".htmlentities ($row['name'], ENT_COMPAT, "UTF-8", false)."\" class=\"textfield\" />\n";

      $layout = htmlentities ($row['xslt'], ENT_COMPAT, "UTF-8", true);
?>
        <label>Layout</label>
        <textarea id="xslt" name="sublayout"><?=$layout ?></textarea>
        <script type="text/javascript">
          //<![CDATA[
            var editor = CodeMirror.fromTextArea (document.getElementById ("xslt"), { mode: { name: "xmlpure" } });
          //]]>
        </script>
<?php
    }
  mysql_free_result ($result);
?>
      </div>
<?php
}
?>
      <p class="alignright operate">
        &nbsp;<br />
<?php
if (!empty ($tid) && empty ($slid))
{
?>
        <input type="hidden" name="tid" value="<?=$tid ?>" />
<?php
if (getsetting ($connection, "use_datasheets") == 1)
{
?>
        <input type="hidden" name="datasheetcount" value="<?=$datasheetcount ?>" />
<?php
} /* getsetting ($connection, "use_datasheets") == 1 */
?>
        <input type="hidden" name="fieldcount" value="<?=$fieldcount ?>" />
        <input type="hidden" name="filecount" value="<?=$filecount - 1 ?>" />
        <input type="hidden" name="stylecount" value="<?=$stylecount - 1 ?>" />
        <input type="hidden" id="show" name="show" value="<?=isset ($_GET['show']) ? $_GET['show'] : 1; ?>" />
<?php
}
else if (empty ($tid) && !empty ($slid))
{
?>
        <input type="hidden" name="slid" value="<?=$slid ?>" />
<?php
}
?>
        <input type="submit" value="Save" class="button" />
      </p>
    </form>
<?php
}
?>
</div>

<div class="clear"></div>

<script type="text/javascript">
  // <![CDATA[
    switchtabs ('<?=isset ($_GET['show']) ? "tab{$_GET['show']}" : "tab1"; ?>');
  // ]]>
</script>
<?php
}
?>
